package com.cwt_taxi_xa;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.ErrorCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.service.DvrService;
import com.cwt_taxi_xa.service.FloatService;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.TTsFunction;
import com.cwt_taxi_xa.util.VolumeControl;
import com.cwt_taxi_xa.util.baidu.FaceMatch;
import com.cwt_taxi_xa.util.baidu.FileUtil;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class ActivityCamera extends CWTBaseActivity{

	private SurfaceView mSurfaceView;
	SurfaceHolder sholder;
	Camera camera;
    Camera.Parameters parameters;
	
	ImageView iv_retrun,iv_cam,iv_loc;
	
	TextView tv_wait;
	
	
	Button bt, bt2;
	
	int cameratrycount = 0;
	
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what==1001){
				VolumeControl.playSound();
				paizhao();
				handler.sendEmptyMessageDelayed(100101, 2000);
			}
			if (msg.what==100101) {
				if (datas==null) {
					if(cameratrycount>10){
						TTsFunction.speakText("TV in 异常");
						return;
					}else{
						cameratrycount++;
					}
					try {
						camera.stopPreview();
						AppLog.e("--------------->>stopPreview");
					} catch (Exception e2) {
						e2.printStackTrace();
					}
					try {
						camera.release();
						AppLog.e("--------------->>release");
					} catch (Exception e2) {
						e2.printStackTrace();
					}
					
					
					try {
						camera = Camera.open(3);
						
						parameters = camera.getParameters();
						parameters.setPreviewSize(701, 501);
						camera.setParameters(parameters);
						camera.setPreviewDisplay(sholder);
						camera.startPreview();
						
						new Thread(new Runnable() {
							
							@Override
							public void run() {
								try {
									Thread.sleep(1500);
								} catch (Exception e) {
								}
								paizhao();
								handler.sendEmptyMessageDelayed(100101, 2000);
							}
						}).start();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}
			if(msg.what==1002){
				bt.setEnabled(true);
				String str = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(str);
					int code = json.getInt("error_code");
					if(code==0){
						json = json.getJSONObject("result");
						double result = json.getDouble("score");
						if(result>35){
//							TTsFunction.speakText("验证成功");
////							ActivityWaitQD.face = true;
//							SerialPortService.getInstance().sendSerialData6(
//									MeterEncoder.sendDriverInfoForPower905("00E0",
//											"", 
//											"", 
//											SPUtils.getParamString(SPConstants.SPK_carcode, SPConstants.SPV_carcode), 
//											DateUtil.getNowDateToMeter(), 1,
//											"0000000000", "0000", "90"));
//							startActivity(new Intent(ActivityCamera.this,
//									ActivityMain.class));
							FloatService.sendpictype = 4;
							FloatService.seq = 0;
							FloatService.w = 640;
							FloatService.h = 480;
							FloatService.channelId = 2;
							
							FloatService.sendPic(datas);
							setResult(123);
							finish();
						}else{
							TTsFunction.speakText("验证失败,非司机本人");
						}
					}else{
//						TTsFunction.speakText("验证失败      "+json.getString("error_msg"));
						TTsFunction.speakText("验证失败");
					}
					
				} catch (Exception e) {
					e.printStackTrace();
					TTsFunction.speakText("验证失败");
				}
				
				
				
				
			}
			if(msg.what==1003){
				Bitmap bitmap = (Bitmap) msg.obj; 
				if(bitmap!=null){
					iv_cam.setImageBitmap(bitmap);
//					iv_cam.setImageBitmap(cropBitmap(bitmap));
				}
			}
			
			if(msg.what==1004){
				tv_wait.setVisibility(View.VISIBLE);
			}
			if(msg.what==1005){
				tv_wait.setVisibility(View.GONE);
				mSurfaceView.callOnClick();
			}
			
			if(msg.what==1010){
				//当前未签到界面，收到计价器已开机心跳，同步状态
				TTsFunction.speakText("同步计价器状态");
				SPUtils.setParam(SPConstants.SPK_signin, true);
				startActivity(new Intent(ActivityCamera.this, ActivityMain.class));
				camera.stopPreview();
				camera.release();
				finish();
			}
			
		};
	};
	
	long lastyl = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_aa_video3);
		
		iv_retrun = (ImageView) findViewById(R.id.imageView7);
		iv_cam = (ImageView) findViewById(R.id.imageView1);
		iv_loc = (ImageView) findViewById(R.id.imageView2);
		tv_wait = (TextView) findViewById(R.id.tv_wait);
		
		
		bt2 = (Button) findViewById(R.id.bt2);
		bt2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(System.currentTimeMillis()-lastyl<1000) return;
				lastyl = System.currentTimeMillis();
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							DvrService.signtime = System.currentTimeMillis()-(1000*60*60-5);
							DvrService.getInstance().onClick(14);
							Thread.sleep(200);
							DvrService.getInstance().onClick(14);
							Thread.sleep(200);
							DvrService.getInstance().onClick(14);
							Thread.sleep(200);
							DvrService.getInstance().sendFaceView(0);
							Thread.sleep(200);
							DvrService.getInstance().sendFaceView(0);
						} catch (Exception e) {
						}
					}
				}).start();
			}
		});
		
		bt = (Button) findViewById(R.id.bt);
		bt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				TTsFunction.speakText("请看摄像头");
				if(MyStatus.online){
					handler.sendEmptyMessageDelayed(1001, 2000);
					bt.setEnabled(false);
				}else{
					TTsFunction.speakText("网络未连接");
					finish();
				}
			}
		});
		
//		Bitmap bitmap = getLoacalBitmap(Constants.sijiinfo.getPhoto()); 
//		if(bitmap!=null){
//			iv_loc.setImageBitmap(bitmap);
//		}
		
		mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
		
		iv_retrun.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				camera.stopPreview();
				camera.release();
				//setResult(123);//调试
				finish();
			}
		});
		
		
//		HashMap<String, UsbDevice> deviceHashMap = ((UsbManager) getSystemService(USB_SERVICE)).getDeviceList();
//		if(deviceHashMap.size()<3){
//			TTsFunction.speakText("摄像头未连接");
//			Toast.makeText(ActivityCamera.this, "摄像头未连接", 1000).show();
//			finish();
//		}else{
		
		
		
			mSurfaceView.getHolder().addCallback(new Callback() {
				
				@Override
				public void surfaceDestroyed(SurfaceHolder arg0) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void surfaceCreated(SurfaceHolder holder) {
					// TODO Auto-generated method stub
					
					
					try {
						sholder = holder;
						
						camera = Camera.open(3);
						
						camera.setErrorCallback(new ErrorCallback() {
							@Override
							public void onError(int arg0, Camera cameraE) {
								AppLog.e("--------------->>onError");
								handler.sendEmptyMessage(1004);
								handler.sendEmptyMessageDelayed(1005, 1500);
//							try {
//								cameraE.stopPreview();
//								AppLog.e("--------------->>stopPreview");
//							} catch (Exception e2) {
//								e2.printStackTrace();
//							}
//							try {
//								cameraE.release();
//								AppLog.e("--------------->>release");
//							} catch (Exception e2) {
//								e2.printStackTrace();
//							}
//							AppLog.e("--------------->>sleepEnd");
//							camera = Camera.open(0);
//							AppLog.e("--------------->>open");
//							new Thread(new Runnable() {
//								public void run() {
//									try {
//										Thread.sleep(6000);
//									} catch (Exception e2) {
//										e2.printStackTrace();
//									}
//								}
//							}).start();
							}
						});
						
						parameters = camera.getParameters();
						
						//获取预览的各种分辨率
//						List<Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes(); 
//						for(Size s: supportedPreviewSizes){
//							AppLog.e(s.width+"-----------"+s.height);
//						}
						//友浩系统的奇葩设定。。。
                    parameters.setPreviewSize(701, 501);
                    camera.setParameters(parameters);
						camera.setPreviewDisplay(sholder);
						camera.startPreview();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				@Override
				public void surfaceChanged(SurfaceHolder holder, int arg1, int arg2, int arg3) {
					// TODO Auto-generated method stub
					sholder = holder;
				}
			});
//		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		mSurfaceView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
//				camera.takePicture(new ShutterCallback() {
//					
//					@Override
//					public void onShutter() {
//						// TODO Auto-generated method stub
//						
//					}
//				}, null, new PictureCallback() {
//					
//					@Override
//					public void onPictureTaken(final byte[] arg0, Camera arg1) {
//						new Thread(new Runnable() {
//							@Override
//							public void run() {
//								// TODO Auto-generated method stub
//								FaceMatch.match(arg0);
//							}
//						}).start();
//					}
//				});
				
				try {
					camera.stopPreview();
					camera.release();
				} catch (Exception e2) {
					// TODO: handle exception
				}
				
				//友浩系统的奇葩设定。。。
            	camera = Camera.open(0);
            	AppLog.e("--------------->>onClick");
            	
//                parameters = camera.getParameters();
                
              //获取预览的各种分辨率
//                List<Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes(); 
//                for(Size s: supportedPreviewSizes){
//                	AppLog.e(s.width+"-----------"+s.height);
//                }
                //友浩系统的奇葩设定。。。
//                parameters.setPreviewSize(chl, 501);
//                camera.setParameters(parameters);
                try {
					camera.setPreviewDisplay(sholder);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                camera.startPreview();
				
			}
		});
		
		
		
		
		
		
		
		
	}
	
	
	
	
	
	
	
	
	
	
	byte[] locpicdata;
	Bitmap locpicbitmap;
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//locpicdata = getIntent().getByteArrayExtra("pic");
		try {
			//应该在线程中执行吧!!
			locpicdata = FileUtil.readFileByBytes(Constants.sijiinfo.getPhoto());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			locpicbitmap=BitmapFactory.decodeByteArray(locpicdata, 0, locpicdata.length);
			if(locpicbitmap==null){
				TTsFunction.speakText("获取司机照片为空");
				finish();
			}
		} catch (Exception e) {
			e.printStackTrace();
			TTsFunction.speakText("获取司机照片出错");
			finish();
		}
		
		iv_loc.setImageBitmap(locpicbitmap);
		
		DvrService.getInstance().sendFaceView(0);
		
		if(MyStatus.online){
			handler.sendEmptyMessageDelayed(1001, 3500);
			bt.setEnabled(false);
		}else{
			TTsFunction.speakText("网络未连接");
			Toast.makeText(ActivityCamera.this, "网络未连接", 1000).show();
			finish();
		}
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
		DvrService.getInstance().sendFaceView(1);
		
		finish();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		try {
			if(camera!=null){
				camera.stopPreview();
				camera.release();
				camera = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	 byte[] datas;
	void paizhao(){
		AppLog.e("拍照卡死---1");
		try {
			
//			Bitmap bmp=loadBitmapFromView(mSurfaceView);
////			bmp = cropBitmap(bmp);
//			
//			handler.sendMessage(handler.obtainMessage(1003, bmp));
//			
//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
//			bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//			datas = baos.toByteArray();
//			
//			new Thread(new Runnable() {
//				@Override
//				public void run() {
////				String json = FaceMatch.detect(arg0);
//					TTsFunction.speakText("正在验证，请稍后。");
//
//					String json = FaceMatch.match(datas, locpicdata);
//					AppLog.e("--------------->"+json);
//					handler.sendMessage(handler.obtainMessage(1002, json));
//				}
//			}).start();
			
			camera.takePicture(new ShutterCallback() {
				
				@Override
				public void onShutter() {
					// TODO Auto-generated method stub
					
				}
			}, null, new PictureCallback() {
				
				@Override
				public void onPictureTaken(final byte[] arg0, Camera arg1) {
					// TODO Auto-generated method stub
					AppLog.e("拍照卡死---2");
					Bitmap bmp=BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
					bmp = cropBitmap(bmp);
					
					handler.sendMessage(handler.obtainMessage(1003, bmp));
					
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
					datas = baos.toByteArray();
					
					new Thread(new Runnable() {
						@Override
						public void run() {
//						String json = FaceMatch.detect(arg0);
							TTsFunction.speakText("正在验证，请稍后。");

							String json = FaceMatch.match(datas, locpicdata);
							AppLog.e("--------------->"+json);
							handler.sendMessage(handler.obtainMessage(1002, json));
						}
					}).start();
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
//		private Bitmap loadBitmapFromView(View v) {
//			int w=v.getWidth();
//			int h=v.getHeight();
//			Bitmap bmp=Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
//			Canvas c= new Canvas(bmp);
////			c.drawColor(Color.WHITE);
//			/** 如果不设置canvas画布为白色，则生成透明 */
//			v.layout(0,0,w,h);
//			v.draw(c);
//			return bmp;
//		}



	public static Bitmap cropBitmap(Bitmap bitmap) {//截取左上角四分之一
		int w = bitmap.getWidth(); // 得到图片的宽，高
		int h = bitmap.getHeight();
		return Bitmap.createBitmap(bitmap, w/4, 0, w/4, h/4, null, false);
	}
	
	/**
	    * 加载本地图片
	    * @param url
	    * @return
	    */
	    public static Bitmap getLoacalBitmap(String url) {
	         try {
	              FileInputStream fis = new FileInputStream(url);
	              return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片        
	         } catch (Exception e) {
	              e.printStackTrace();
	              return null;
	         }
	    }
	
	
	
	
	@Override
	public void setStatus(int index, boolean status) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sendMsg(int type, Object obj) {
		// TODO Auto-generated method stub
		if (type == 1011){
			if((Boolean)obj){
				handler.sendMessage(handler.obtainMessage(1010));
			}
		}
	}

}
